// 引入Food类
import Food from './Food'
// 引入Food类
import Snake from './Snake'

export default class GameControl{
    food:Food;
    snake:Snake;
    direction:string = '';

    X:number = 0;
    Y:number = 0;

    shijian:unknown;

    constructor(){
        this.food = new Food()
        this.snake = new Snake()
    }

    start(){
        document.addEventListener('keydown', this.shijian = this.keyBoardEvent.bind(this))
    }
    keyBoardEvent(e:KeyboardEvent){
        e.preventDefault()
        this.direction = e.key
        this.run()
    }
    run(){
        this.X = this.snake.X
        this.Y = this.snake.Y
        switch(this.direction){
            case 'ArrowUp':
                 this.Y -= 10
                 break;
            case 'ArrowDown':
                 this.Y += 10
                 break;
            case 'ArrowLeft':
                 this.X -= 10
                 break;
            case 'ArrowRight':
                 this.X += 10
                 break;
            default:
                 return;
        }

        // 碰撞检测处理
        try {
            this.checkCollision(this.X,this.Y)
        } catch (error) {
            alert(error)
            document.removeEventListener('keydown',this.shijian as EventListener)
            return;
        }

        // 吃到食物处理
        this.checkEatFood(this.X,this.Y)

        // 身体移动
        this.snake.moveBodies()
        // 蛇头移动
        this.snake.X = this.X
        this.snake.Y = this.Y
        
    }
    // 碰撞检测
    checkCollision(X:number,Y:number){
        if(X < 0 || X > 290 || Y < 0 || Y > 290){
            throw new Error('game over')
        }
        for(let i = 0; i < this.snake.bodies.length; i++){
            if(X === (this.snake.bodies[i] as HTMLElement).offsetLeft && 
            Y === (this.snake.bodies[i] as HTMLElement).offsetTop){
                throw new Error('game over')
            }
        }
    }

    // 吃到食物
    checkEatFood(X:number,Y:number){
        if(X === this.food.foodX && Y === this.food.foodY){
            this.food.change()
            this.snake.addBodies()
        }
    }
}